package com.euond.accv.gateway.filter;

import com.euond.accv.gateway.constant.FilterConstants;
import com.euond.accv.gateway.service.TokenService;
import com.euond.accv.gateway.utils.Utils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 验证AccessToken是否合法
 *
 * 对请求进行拦截与过滤
 * filterOrder:filter执行顺序，通过数字指定 
   shouldFilter:filter是否需要执行 true执行 false 不执行 
    run : filter具体逻辑 
	filterType :filter类型,分为以下几种
 */
public class AccessTokenFilter extends ZuulFilter {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	@Autowired
	private TokenService tokenService;

	/**
	 * 是否执行run方法
	 */
	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public Object run() {
		logger.info("run AccessToken Filter.....");

		RequestContext ctx = RequestContext.getCurrentContext();
		ctx.addZuulResponseHeader("Content-Type","application/json;charset=UTF-8");

        HttpServletRequest request = ctx.getRequest();
        String accessToken = request.getParameter("accessToken");
		if(accessToken == null) {
			String resultStr = Utils.resultJson("1010","accessToken不允许为空!");
			ctx.setResponseBody(resultStr);
			ctx.setSendZuulResponse(false);
			ctx.set(FilterConstants.STATUS_CODE,"1010");
            return null;
        }else{
			//验证token是否有效
			Map<String,String> dev = tokenService.getCustomerDev(accessToken);
			if(dev == null){
				String resultStr = Utils.resultJson("1020","AccessToken令牌无效或已过期");
				ctx.setResponseBody(resultStr);
				//过滤该请求，不往下级服务去转发请求，到此结束
				ctx.setSendZuulResponse(false);
				ctx.set(FilterConstants.STATUS_CODE,"1020");
				return null;
			}
			ctx.set(FilterConstants.STATUS_CODE,"0");
			ctx.set(FilterConstants.RESULT,dev);
			return dev;
		}
	}


	/**
	 * 	pre:请求执行之前filter 
		route: 处理请求，进行路由 
		post: 请求处理完成后执行的filter 
		error:出现错误时执行的filter
	 */
	@Override
	public String filterType() {
		return FilterConstants.PRE_TYPE;
	}

	@Override
	public int filterOrder() {
		return 20;
	}

}
